package com.yingxin.yx.framework.commons.helper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 小计 helper
 */
public class SubTotalHelper {

    /**
     * 合计row标识
     */
    public static final String subtotalFlag = "subtotalFlag";

    /**
     * @param list          列表数据
     * @param subtotalMap   map key 小计字段值 map value 小计对象
     * @param subtotalField 小计字段
     * @param <T>
     * @return
     */
    public static <T> List<T> subtotal(List<T> list, Map<String, T> subtotalMap, String subtotalField) {
        // recordIndexMap 记录插入小计的idx
        Map<String, Integer> recordIndexMap = new HashMap<>();
        // orderList 维持顺序
        List<T> orderList = new ArrayList<>();
        String key = null;
        int floor = 0;
        for (int i = 0; i < list.size(); i++) {
            T t = list.get(i);
            String subtotalFieldVal = (String) ClassHelper.getFieldVal(t, subtotalField);
            if (!subtotalFieldVal.equals(key)) {
                if (key != null) {
                    floor++;
                    recordIndexMap.put(key, i - 1 + floor);// 插入i的前面
                    orderList.add(subtotalMap.get(key));
                }
                key = subtotalFieldVal;
            }
            if (i == list.size() - 1) {
                floor++;
                recordIndexMap.put(key, i + floor);// 插入i的后面
                orderList.add(subtotalMap.get(key));
            }
        }
        for (T t : orderList) {
            ClassHelper.setFieldVal(t, subtotalFlag, "1");
            String k = (String) ClassHelper.getFieldVal(t, subtotalField);
            // idx
            int idx = recordIndexMap.get(k);
            list.add(idx, t);
        }
        return orderList;
    }

}